String.prototype.replaceAll = function (match, replace) {
    var regExp = new RegExp(match, 'gm');
    return this.replace(regExp, replace);
};

function initCommentTab() {
    var $items = $('div.comment-item');
    var tabSize = 6;
    if ($items.length < tabSize) {
        return false;
    }
    var tabLength = parseInt($items.length / tabSize + 1);
    $items.hide();
    $items.each(function (i, item) {
        var className = 'comment-tab-' + parseInt(i / tabSize + 1);
        $(item).addClass(className);
    });
    var $pager = $('<div class="comment-pager"></div>');
    for (var i = 1; i <= tabLength; i++) {
        $pager.append('<a rel="comment-page-' + i + '" href="#">' + i + '</a>');
    }
    $('.comment-tab-' + tabLength).show();
    var $cm = $('#comment');
    $cm.prepend($pager).css('min-height', $cm.height());
    $('a[rel=comment-page-' + tabLength + ']').addClass('current');
    $('.comment-pager').on('click', 'a', function (e) {
        e.preventDefault();
        if ($(this).hasClass('current')) {
            return false;
        }
        var tabClass = $(this).attr('rel').replace('page', 'tab');
        $items.hide();
        $('.' + tabClass).fadeIn(250);
        $('.comment-pager .current').removeClass('current');
        $(this).addClass('current');
        return false;
    });
    return true;
}

function initCommentForm() {
    var $form = $('#comment-form');
    if ($form.length < 1) {
        return false;
    }
    localStorage.time = parseInt((new Date()).getTime() / 1000);

    var tpl = '<div class="comment-item" id="{id}">';
    tpl += '<img class="avatar" src="{avatar}" alt="{author}"/>';
    tpl += '<p class="meta"><a class="name" href="#">{author}</a>';
    tpl += '<span class="time">刚刚</span>';
    tpl += '<span class="status">{status}</span>';
    tpl += '<div class="content">{content}</div></div>';

    function resetForm() {
        $('#comment-author').val(localStorage.name);
        $('#comment-email').val(localStorage.email);
        $('#comment-url').val(localStorage.url);
        $('#comment-content').val('');
        $('#comment-parent').val(0);
    }

    resetForm();
    $.getScript('/public/js/validator.js', function () {
        $form.validator({
            singleError: true,
            position: 'top right',
            messageClass: 'comment-error',
            offset: [8, -42],
            onFail: function (e, error) {
                $(error[0].input).focus();
                return true;
            }
        }).on('submit', function (e) {
                if (!e.isDefaultPrevented()) {
                    localStorage.name = $('#comment-author').val();
                    localStorage.email = $('#comment-email').val();
                    localStorage.url = $('#comment-url').val();
                    $.ajax({
                        type: 'post',
                        data: $form.serialize(),
                        dataType: 'json',
                        headers: {
                            'X-Time': localStorage.time
                        },
                        success: function (json) {
                            if (!json.result) {
                                $('#comment-submit').val(json.message).addClass('error');
                                setTimeout(function () {
                                    $('#comment-submit').val('Post Comment')
                                        .removeClass('error');
                                }, 2500);
                            } else {
                                var comment = json.comment;
                                var html = tpl.replaceAll('{id}', comment.id)
                                    .replaceAll('{author}', comment.author)
                                    .replaceAll('{avatar}', comment.avatar)
                                    .replaceAll('{status}', comment.status != 'public' ? '您的评论需要审核' : '')
                                    .replaceAll('{content}', comment.content);
                                $('#comment-content').val('');
                                $('#comment-parent').val(0);
                                $('#comment-reply').html(html).show(200);
                                localStorage.time = parseInt((new Date()).getTime() / 1000);
                            }
                        }
                    });
                    e.preventDefault();
                }
            });
    });
    $('#comment').on('click', '.reply',function () {
        var id = $(this).attr('rel');
        var $cmt = $('#comment-' + id).clone();
        var $reply = $('#comment-reply');
        $cmt.find('.comment-children').remove();
        $cmt.find('.floor').remove();
        $cmt.find('.reply').text('取消回复').removeClass('reply').addClass('no-reply');
        $reply.slideUp(200).html('<div class="comment-item">' + $cmt.html() + '</div>').delay(150).slideDown(200);
        $('body').animate({
            scrollTop: $('#comment-form').offset().top - 140
        }, 500);
        $('#comment-parent').val(id);
        return false;
    }).on('click', '.no-reply', function () {
            $('#comment-reply').empty().slideUp(200);
            $('#comment-parent').val(0);
            return false;
        });
    return true;
}

$(document).ready(function () {
    initCommentTab();
    initCommentForm();
});
